package com.atlin.project.service.impl;


import com.alipay.api.domain.AlipayTradePagePayModel;
import com.atlin.project.common.ErrorCode;
import com.atlin.project.contant.CommonConstant;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.manager.AlipayManager;
import com.atlin.project.model.domain.BiProducts;
import com.atlin.project.model.domain.BiProductsOrder;
import com.atlin.project.model.domain.SysUser;
import com.atlin.project.model.dto.biProduces.BiProductsOrderQueryRequest;
import com.atlin.project.model.enums.biProduces.BiProductsOrderStatusEnum;
import com.atlin.project.service.BiProductsOrderService;
import com.atlin.project.mapper.BiProductsOrderMapper;
import com.atlin.project.service.BiProductsService;
import com.atlin.project.service.ServiceUsageService;
import com.atlin.project.utils.sql.SqlUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @author atlin
 * @description 针对表【bi_products_order(BI商品订单表)】的数据库操作Service实现
 * @createDate 2024-11-25 16:25:56
 */
@Service
@Slf4j
public class BiProductsOrderServiceImpl extends ServiceImpl<BiProductsOrderMapper, BiProductsOrder>
        implements BiProductsOrderService {

    @Resource
    private BiProductsService biProductsService;

    @Resource
    private AlipayManager alipayManager;

    @Resource
    private ServiceUsageService serviceUsageService;

    @Override
    @Transactional
    public String placeAnOrder(Long productsId, SysUser sysUser) {
        BiProducts biProducts = biProductsService.getById(productsId);
        if (biProducts == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "此产品不存在");
        }

        BiProductsOrder biProductsOrder = new BiProductsOrder();
        biProductsOrder.setBiProduceId(biProducts.getId());
        biProductsOrder.setUserId(sysUser.getId());
        biProductsOrder.setTotalPrice(biProducts.getPrice());
        biProductsOrder.setStatus(BiProductsOrderStatusEnum.TO_BE_PAID.getValue());
        boolean save = save(biProductsOrder);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下单失败稍后再试");
        }

        // 填充业务参数
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(biProductsOrder.getId().toString());
        model.setTotalAmount(biProductsOrder.getTotalPrice().toString());
        model.setSubject(biProducts.getName());
        model.setBody(biProducts.getDescription());
        String payRes = alipayManager.pay(model);
        if (StringUtils.isBlank(payRes)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下单失败，稍后再试");
        }

        return payRes;
    }

    @Override
    public void paymentHandle(Long biProductsOrderId, BiProductsOrderStatusEnum biProductsOrderStatusEnum) {
        paymentHandle(biProductsOrderId, null, biProductsOrderStatusEnum);
    }

    @Override
    public void paymentHandle(Long biProductsOrderId, String tradeNo, BiProductsOrderStatusEnum biProductsOrderStatusEnum) {
        if (biProductsOrderId == null) {
            log.error("支付回调处理失败,biProductsOrderId参数不存在");
            return;
        }

        BiProductsOrder biProductsOrder = getById(biProductsOrderId);
        if (biProductsOrder == null) {
            log.error("支付回调处理失败,biProductsOrderId:{} 订单不存在", biProductsOrderId);
            return;
        }

        BiProducts biProducts = biProductsService.getById(biProductsOrder.getBiProduceId());
        if (biProducts == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "此产品不存在");
        }

        biProductsOrder.setStatus(biProductsOrderStatusEnum.getValue());
        if (StringUtils.isNotBlank(tradeNo)) {
            biProductsOrder.setTradeNo(tradeNo);
        }
        boolean save = updateById(biProductsOrder);
        if (!save) {
            log.error("支付回调处理失败,订单状态修改失败,biProductsOrderId:{},tradeNo:{}", biProductsOrderId, tradeNo);
        }
        Boolean updated = serviceUsageService.updateTokens(biProductsOrder.getUserId(), biProducts.getTokens(), false);
        if (!updated) {
            log.error("支付回调处理失败,服务Token增加失败,biProductsOrderId:{},tradeNo:{}", biProductsOrderId, tradeNo);
        }
    }

    /**
     * 获取查询包装类（用户根据哪些字段查询，根据前端传来的请求对象，得到 mybatis 框架支持的查询 QueryWrapper 类）
     *
     * @param biProductsOrderQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<BiProductsOrder> getQueryWrapper(BiProductsOrderQueryRequest biProductsOrderQueryRequest) {
        QueryWrapper<BiProductsOrder> queryWrapper = new QueryWrapper<>();
        if (biProductsOrderQueryRequest == null) {
            return queryWrapper;
        }
        Long id = biProductsOrderQueryRequest.getId();
        String sortField = biProductsOrderQueryRequest.getSortField();
        String sortOrder = biProductsOrderQueryRequest.getSortOrder();
        Long biProduceId = biProductsOrderQueryRequest.getBiProduceId();
        Long userId = biProductsOrderQueryRequest.getUserId();
        BigDecimal totalPrice = biProductsOrderQueryRequest.getTotalPrice();
        Integer status = biProductsOrderQueryRequest.getStatus();
        Date createTime = biProductsOrderQueryRequest.getCreateTime();
        Date updateTime = biProductsOrderQueryRequest.getUpdateTime();
        
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(biProduceId), "biProduceId", biProduceId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(totalPrice), "totalPrice", totalPrice);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.ge(ObjectUtils.isNotEmpty(createTime), "createTime", createTime);
        queryWrapper.eq("isDelete", false);
        
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        
        return queryWrapper;
    }
}




